package com.example.musicplayer;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.musicplayer.activity.BaseActivity;
import com.example.musicplayer.activity.LoginActivity;
import com.example.musicplayer.activity.MainActivity;
import com.example.musicplayer.commonUtils.Timer;
import com.example.musicplayer.dialogTools.NormalAlertDialog;
import com.example.musicplayer.service.DesktopLyricService;
import com.example.musicplayer.service.MusicTabViewService;
import com.example.musicplayer.settings.MusicPlayerSettings;
import com.example.musicplayer.user.UserManage;

import java.util.ArrayList;
import java.util.List;

public class MusicPlayerApplication extends Application {
    private static final String TAG = "MusicPlayerApplication";
    private static int sRefreshTime;
    private static int sRefreshTimeSpare;
    private static int sTimerRefreshTime;
    private static int sAnimationTime;
    private static int sAppAnimationTime;
    private static MusicPlayerApplication sInstance;
    private MusicPlayerLifecycleCallbacks mLifecycleCallbacks;
    private Bitmap mScreenShot;
    private boolean mStopTimerThread;
    private List<Timer> mTimers;
    private final Object mTimerObject = new Object();

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
        sRefreshTime = sInstance.getResources().getInteger(R.integer.music_tab_view_refresh_time);
        sRefreshTimeSpare = sInstance.getResources().getInteger(R.integer.refresh_time_spare);
        sTimerRefreshTime = sRefreshTimeSpare;
        sAnimationTime = sInstance.getResources().getInteger(R.integer.music_tab_view_animation_time);
        sAppAnimationTime = sInstance.getResources().getInteger(R.integer.app_animation_time);
        //注册回调监听
        mLifecycleCallbacks = new MusicPlayerLifecycleCallbacks();
        this.registerActivityLifecycleCallbacks(mLifecycleCallbacks);
        mTimers = new ArrayList<Timer>();
        mStopTimerThread = false;
        startTimerThread();
    }

    private void startTimerThread() {
        new Thread() {
            @Override
            public void run() {
                while (!mStopTimerThread) {
                    try {
                        int currentRefreshTime;
                        synchronized (mTimerObject) {
                            currentRefreshTime = sTimerRefreshTime;
                        }
                        Thread.sleep(currentRefreshTime);
                        for (Timer timer : mTimers) {
                            if (timer != null && timer.getHandler() != null) {
                                if (timer.update(currentRefreshTime)) {
                                    timer.getHandler().sendEmptyMessage(Timer.UPDATE);
                                }
                            } else {
                                removeTimer(timer);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    private void stopTimerThread() {
        mStopTimerThread = true;
    }

    private void addOrRemoveTimer(Timer timer, boolean isAdd) {
        int size = mTimers.size();
        //re calculate the refresh time
        boolean changed = false;
        mTimers.remove(null);
        if (size != mTimers.size()) {
            size = mTimers.size();
            changed = true;
        }
        if (isAdd && timer != null && !mTimers.contains(timer)) {
            mTimers.add(timer);
        }
        if (!isAdd) {
            mTimers.remove(timer);
        }
        if (size != mTimers.size()) {
            changed = true;
        }
        if (changed) {
            synchronized (mTimerObject) {
                if (mTimers.size() == 0) {
                    sTimerRefreshTime = sRefreshTimeSpare;
                } else {
                    sTimerRefreshTime = mTimers.get(0).getInterval();
                    for (int i = 1; i < mTimers.size(); i++) {
                        if (mTimers.get(i).getInterval() < sTimerRefreshTime) {
                            sTimerRefreshTime = mTimers.get(i).getInterval();
                        }
                    }
                    sTimerRefreshTime = Math.min(sTimerRefreshTime, sRefreshTimeSpare);
                }
            }
        }
    }

    public static MusicPlayerApplication getInstance() {
        return sInstance;
    }

    public static void addTimer(Timer timer) {
        sInstance.addOrRemoveTimer(timer, true);
    }

    public static void removeTimer(Timer timer) {
        sInstance.addOrRemoveTimer(timer, false);
    }

    //判断应用是否位于前台
    public boolean isForeground() {
        return mLifecycleCallbacks.getForeground();
    }

    //退出应用
    public void exit() {
        //退出前保存数据
        if (DataLoadManager.getInstance() != null) {
            DataLoadManager.getInstance().writeBaseData();
        }
        //remove the service views
        Binder binder = getMusicTabViewServiceBinder();
        if (binder instanceof MusicTabViewService.MusicTabViewBinder) {
            ((MusicTabViewService.MusicTabViewBinder) binder).showViewDirectly(false);
        }
        binder = getDesktopLyricServiceBinder();
        if (binder instanceof DesktopLyricService.DesktopLyricBinder) {
            ((DesktopLyricService.DesktopLyricBinder) binder).showDesktopLyricView(false);
        }
        ActivityStackManager.getInstance().exit();
    }

    //exit login state
    public void exitLogin() {
        UserManage.exitLoginState();
        MusicPlayerSettings.exitLoginState();
        Activity activity;
        ActivityStackManager manager = ActivityStackManager.getInstance();
        while (manager.getStackSize() > 0) {
            activity = manager.getTopActivity();
            if (activity != null) {
                if (activity instanceof MainActivity) {
                    activity.startActivity(new Intent(activity, LoginActivity.class));
                }
                if (!activity.isFinishing()) {
                    activity.finish();
                }
                manager.removeActivity(activity);
            }
        }
    }

    public MainActivity getMainActivity() {
        Activity activity = ActivityStackManager.getInstance().getMainActivity();
        if (activity instanceof MainActivity) {
            return (MainActivity) activity;
        }
        return null;
    }

    public Activity getTopActivity() {
        return ActivityStackManager.getInstance().getTopActivity();
    }

    public Binder getMusicServiceBinder() {
        MainActivity mainActivity = getMainActivity();
        if (mainActivity != null) {
            return mainActivity.tryGetMusicBinder();
        }
        return null;
    }

    public Binder getMusicTabViewServiceBinder() {
        MainActivity mainActivity = getMainActivity();
        if (mainActivity != null) {
            return mainActivity.tryGetMusicTabViewBinder();
        }
        return null;
    }

    public Binder getDesktopLyricServiceBinder() {
        MainActivity mainActivity = getMainActivity();
        if (mainActivity != null) {
            return mainActivity.tryGetDesktopLyricBinder();
        }
        return null;
    }

    public Bitmap getScreenShot() {
        return mScreenShot;
    }

    public void setScreenShot(Bitmap bitmap) {
        mScreenShot = bitmap;
    }

    public void clearScreenShot() {
        mScreenShot = null;
    }

    public static int getRefreshTime() {
        return sRefreshTime;
    }

    public static int getAnimationTime() {
        return sAnimationTime;
    }

    public static int getAppAnimationTime() {
        return sAppAnimationTime;
    }

    public static NormalAlertDialog showTimedOffPromptDialog() {
        final Activity activity = sInstance.getTopActivity();
        if (activity instanceof BaseActivity) {
            final NormalAlertDialog dialog = new NormalAlertDialog(activity
                    , activity.getString(R.string.prompt)
                    , activity.getString(R.string.timing_set_achieve)
                    , activity.getString(R.string.timing_set_achieve_dialog_left)
                    , activity.getString(R.string.timing_set_achieve_dialog_right));
            dialog.getLeftButton().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    sInstance.exit();
                }
            });
            dialog.getRightButton().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    ((BaseActivity) activity).notExitTemporarily();
                }
            });
            dialog.show();
            return dialog;
        }
        return null;
    }

    public static boolean canDrawOverlays() {
        if (Build.VERSION.SDK_INT >= 23) {
            return Settings.canDrawOverlays(getInstance());
        }
        return false;
    }

    //activity声明周期监听的类
    private static class MusicPlayerLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
        private int mCounts = 0;
        //表示应用是否位于前台
        private boolean mIsForeground = true;

        @Override
        public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
            Log.d(TAG, "onActivityCreated(): " + activity.getLocalClassName());
            ActivityStackManager.getInstance().addActivity(activity);
        }

        @Override
        public void onActivityStarted(@NonNull Activity activity) {
            Log.d(TAG, "onActivityStarted(): " + activity.getLocalClassName());
            changeCounts(true);
            setForeground(true);
        }

        @Override
        public void onActivityResumed(@NonNull Activity activity) {
            Log.d(TAG, "onActivityResumed(): " + activity.getLocalClassName());
        }

        @Override
        public void onActivityPaused(@NonNull Activity activity) {
            Log.d(TAG, "onActivityPaused(): " + activity.getLocalClassName());
        }

        @Override
        public void onActivityStopped(@NonNull Activity activity) {
            Log.d(TAG, "onActivityStopped(): " + activity.getLocalClassName());
            if (changeCounts(false) == 0) {
                setForeground(false);
                String text = getInstance().getString(R.string.app_name) +
                        getInstance().getString(R.string.app_switch_to_background);
                //ToastUtil.makeToast(text);
                Binder binder = getInstance().getMusicTabViewServiceBinder();
                if (binder != null) {
                    ((MusicTabViewService.MusicTabViewBinder) binder).shouldShowView(false);
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (getInstance().getDesktopLyricServiceBinder() != null) {
                                ((MusicTabViewService.MusicTabViewBinder) getInstance().getMusicTabViewServiceBinder())
                                        .shouldShowView(false);
                            }
                        }
                    }, 100);
                }
            }
        }

        @Override
        public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
            Log.d(TAG, "onActivitySaveInstanceState(): " + activity.getLocalClassName());
            if (getInstance().getMainActivity() != null) {
                getInstance().getMainActivity().saveMusicPlayState();
            }
        }

        @Override
        public void onActivityDestroyed(@NonNull Activity activity) {
            Log.d(TAG, "onActivityDestroyed(): " + activity.getLocalClassName());
            ActivityStackManager.getInstance().removeActivity(activity);
            if (activity instanceof MainActivity) {
                ((MainActivity) activity).saveMusicPlayState();
                //ToastUtil.makeToast("退出QQ音乐");
            }
        }

        private synchronized int changeCounts(boolean isIncrease) {
            if (isIncrease)
                mCounts++;
            else
                mCounts--;
            return mCounts;
        }

        private synchronized void setForeground(boolean isForeground) {
            if (mIsForeground != isForeground) {
                mIsForeground = isForeground;
                sInstance.sendBroadcast(new Intent(sInstance.getString(R.string.broadcast_foreground_state_change)));
            }
        }

        public synchronized boolean getForeground() {
            return mIsForeground;
        }
    }
}